package com.rw.coco.event;

import com.rw.coco.CocoPlugin;
import com.rw.coco.api.event.GroupMessageEvent;
import com.rw.coco.api.modle.Account;
import com.rw.coco.api.modle.Bot;
import com.rw.coco.api.modle.Group;
import com.rw.coco.model.KookAccount;
import com.rw.coco.model.KookBot;
import com.rw.coco.model.KookGroup;
import snw.jkook.Permission;
import snw.jkook.entity.User;
import snw.jkook.message.TextChannelMessage;

import java.util.Collection;

public class KookGroupMessageEvent implements GroupMessageEvent {
    private final TextChannelMessage eventMessage;

    public KookGroupMessageEvent(TextChannelMessage eventMessage) {
        this.eventMessage = eventMessage;
    }

    @Override
    public boolean isAdmin() {
        // 是否为群主
        boolean master = eventMessage.getChannel().getMaster().equals(eventMessage.getSender());
        Collection<Integer> roles = eventMessage.getSender().getRoles(eventMessage.getChannel().getGuild());
        // 是否为管理员
        boolean admin = roles.contains(Permission.ADMIN.getValue());

        return master || admin;
    }

    @Override
    public Group getGroup() {
        String id = eventMessage.getChannel().getGuild().getId();
        String name = eventMessage.getChannel().getGuild().getName();
        return new KookGroup(id, name);
    }

    @Override
    public void quit() {
        eventMessage.getChannel().getGuild().leave();
    }

    @Override
    public Bot getBot() {
        User user = CocoPlugin.getInstance().getCore().getUser();
        String name = user.getName();
        String id = user.getId();
        return new KookBot(id, name);
    }

    @Override
    public String getMessage() {
        return eventMessage.getComponent().toString();
    }

    @Override
    public Account getSender() {
        User user = eventMessage.getSender();
        String nickName = user.getNickName(eventMessage.getChannel().getGuild());
        String name = user.getName();
        String id = user.getId();
        return new KookAccount(id, nickName, name);
    }

    @Override
    public void sendBack(String message) {
        eventMessage.reply(message);
    }

    @Override
    public void sendBackSender(String message) {
        eventMessage.getSender().sendPrivateMessage(message);
    }

    @Override
    public void sendPrivate(String message, String accountId) {
        CocoPlugin.getInstance()
                .getCore()
                .getHttpAPI()
                .getUser(accountId)
                .sendPrivateMessage(message);
    }

    @Override
    public void sendGroup(String message, String groupId) {
        CocoPlugin.getInstance()
                .getCore()
                .getHttpAPI()
                .getTextChannelMessage(groupId)
                .sendToSource(message);
    }
}
